import { extend } from 'umi-request';
import { store } from '@/store';

const COMMON_BASE_URL = {
    development: 'http://127.0.0.1:12306',
    production: 'http://host:port',
    test: 'http://host:port',
}[process.env.NODE_ENV as string] as string;

const request = extend({
    prefix: COMMON_BASE_URL,
    errorHandler(err) {
        console.error(err);
        return {};
    },
});

request.interceptors.response.use(async res => {
    try {
        const data = await res.json();
        return data;
    } catch (error: unknown) {
        return {};
    }
});

request.interceptors.request.use((url, options) => {
    const token = store.getState().user.auth?.token;

    if (token) {
        return {
            url,
            options: {
                ...options,
                headers: {
                    ...options.headers,
                    Authorization: `Bearer ${token}`,
                },
            },
        };
    }

    return {
        url,
        options,
    };
});

export default request;
